import api from '@/api/api';
import maps from '@/utils/maps';
export default {
  namespaced: true,
  state: () => ({
    schoolInfo: {},
    schoolOptions: {},
    schoolList: [],
    currentSchoolId: null
  }),
  getters: {
    schoolName: (state) => state.schoolInfo.F_name,
    schoolType: (state) =>
      maps.useTypeList.find((e) => e.id === state.schoolInfo.F_use_type)
        ?.name || '',
    schoolId: (state) => state.schoolInfo.F_id,
    schoolAdmin: (state) => state.schoolInfo.F_admin,
    schoolLocation: (state) => state.schoolInfo.F_loc,
    schoolSubjectList: (state) => state.schoolOptions?.F_subjects || [],
    schoolGradeList: (state) => {
      const list = [];
      const grades = state.schoolOptions?.F_grades || {};
      const gradeList = JSON.parse(JSON.stringify(maps.gradeList));
      gradeList.splice(6, 3, ...[
        { id: 7, name: '初一' },
        { id: 8, name: '初二' },
        { id: 9, name: '初三' },
      ]);
      for (let k of Object.keys(grades)) {
        const grade = gradeList.find((e) => e.id === +k);
        if (grade) {
          list.push(grade);
        }
      }
      return list;
    },
    schoolSubjectCustomSelect: (state, getters) => getters.schoolSubjectList.filter(e => e.is_select === 1 && e.is_foreign === 0),
    schoolSubjectCustomForeignSelect: (state, getters) => getters.schoolSubjectList.filter(e => e.is_select === 1 && e.is_foreign === 1),
    currentSchool: (state) => state.schoolList.find(school => school.F_id === state.currentSchoolId) || (state.schoolList.length > 0 ? state.schoolList[0] : null)
  },
  mutations: {
    SET_SCHOOL_INFO(state, payload) {
      state.schoolInfo = payload.value;
    },
    SET_SCHOOL_OPTIONS(state, payload) {
      state.schoolOptions = payload.value;
    },
    SET_SCHOOL_LIST(state, payload) {
      state.schoolList = payload.value;
      // 如果学校列表不为空，且当前未选择学校，则默认选择第一所学校
      if (state.schoolList.length > 0 && !state.currentSchoolId) {
        state.currentSchoolId = state.schoolList[0].F_id;
      }
    },
    SET_CURRENT_SCHOOL_ID(state, payload) {
      state.currentSchoolId = payload.value;
    },
    // 重置学校相关状态
    RESET_SCHOOL_STATE(state) {
      state.schoolInfo = {};
      state.schoolOptions = {};
      state.schoolList = [];
      state.currentSchoolId = null;
    }
  },
  actions: {
    async GET_SCHOOL_DETAIL({ commit }, payload) {
      const { F_school } = await api.getSchool({
        F_school_id: payload.school_id,
      });
      commit('SET_SCHOOL_INFO', {
        value: F_school,
      });
    },
    async GET_SCHOOL_OPTIONS({ commit, rootGetters }, payload) {
      const schoolId = payload.school_id;
      const sessionKey = `school_subject_${schoolId}`;
      
      // 先从 sessionStorage 读取科目数据
      let subjectList = null;
      try {
        const cachedData = sessionStorage.getItem(sessionKey);
        if (cachedData) {
          subjectList = JSON.parse(cachedData);
          console.log(`从 sessionStorage 读取科目数据，schoolId: ${schoolId}`);
        }
      } catch (e) {
        console.warn('读取 sessionStorage 科目数据失败:', e);
      }

      // 如果 sessionStorage 中没有数据，才调用接口
      if (!subjectList) {
        console.log(`调用接口获取科目数据，schoolId: ${schoolId}`);
        subjectList = await api.getSchoolSubject(schoolId);
        // 将结果存储到 sessionStorage
        try {
          sessionStorage.setItem(sessionKey, JSON.stringify(subjectList));
          console.log(`科目数据已存储到 sessionStorage，schoolId: ${schoolId}`);
        } catch (e) {
          console.warn('存储科目数据到 sessionStorage 失败:', e);
        }
      }

      let { F_grades, F_subjects } = await api.getOptions({
        F_school_id: schoolId,
        F_option: 'grade,subject',
      });

      let retGrades = {};
      const { grade_list, subject_list, class_list } =
        rootGetters['user/userPermission'];

      // 过滤学科列表
      if (subject_list && subject_list.length) {
        subjectList = subjectList.filter((id) =>
          subject_list.find((e) => e.id === id)
        );
      }

      // 过滤年级、班级列表
      if (!grade_list || !grade_list.length) {
        retGrades = JSON.parse(JSON.stringify(F_grades));
      } else {
        for (let [k, v] of Object.entries(F_grades)) {
          if (grade_list.find((e) => e.id === +k)) {
            if (class_list && class_list.length) {
              v = v.filter((e) =>
                class_list.find((u) => u.F_id === e.F_class_id)
              );
            }
            retGrades[k] = v;
          }
        }
      }
      commit('SET_SCHOOL_OPTIONS', {
        value: { F_grades: retGrades, F_subjects: subjectList },
      });
    },
    async GET_SCHOOL_LIST({ commit, rootGetters }) {
      try {
        const { userPermission, isSuperAdmin } = rootGetters;
        let schools = [];
        
        // 如果是超级管理员或区域管理员（level <= 3），获取管理的所有学校
        if (isSuperAdmin || (userPermission && userPermission.level && userPermission.level <= 3)) {
          const res = await api.getSChoolsByAdmin({
            F_page: 1,
            F_limit: 100
          });
          schools = res.F_schools || [];
        } 
        // 如果是学校账户，获取自己所属的学校
        else if (userPermission && userPermission.school_list && userPermission.school_list.length > 0) {
          // 直接使用权限中的学校列表
          schools = userPermission.school_list || [];
          
          // 如果需要获取更详细的学校信息，可以通过ID获取
          if (schools.length > 0) {
            const schoolIds = schools.map(school => school.F_id || school.FID).filter(id => id).join(',');
            if (schoolIds) {
              try {
                const res = await api.getSchoolsByIds({
                  F_school_ids: schoolIds
                });
                // 如果API返回了详细信息，则使用API返回的学校列表
                if (res.F_school && res.F_school.length > 0) {
                  schools = res.F_school;
                }
              } catch (error) {
                // 如果获取详细信息失败，确保使用权限中的基本信息，但需要格式化
                schools = schools.map(school => ({
                  F_id: school.F_id || school.FID,
                  F_name: school.F_name || school.FName,
                  ...school
                }));
              }
            } else {
              // 如果没有有效的学校ID，尝试格式化学校数据
              schools = schools.map(school => ({
                F_id: school.F_id || school.FID,
                F_name: school.F_name || school.FName,
                ...school
              }));
            }
          }
        }
        // 注意：某些页面可能不需要学校列表，这是正常的，不需要警告
        
        commit('SET_SCHOOL_LIST', {
          value: schools
        });
      } catch (error) {
        console.error('获取学校列表失败:', error);
        commit('SET_SCHOOL_LIST', {
          value: []
        });
      }
    },
    SET_CURRENT_SCHOOL({ commit }, schoolId) {
      // 确保schoolId是有效值
      if (!schoolId) {
        console.warn('SET_CURRENT_SCHOOL: 尝试设置无效的学校ID:', schoolId);
        return;
      }
      
      console.log('SET_CURRENT_SCHOOL: 设置当前学校ID:', schoolId);
      commit('SET_CURRENT_SCHOOL_ID', {
        value: schoolId
      });
    },
    // 重置学校状态的action
    RESET_SCHOOL({ commit }) {
      commit('RESET_SCHOOL_STATE');
      // 清除所有学校的科目缓存（登录时清除，确保使用新数据）
      try {
        const keys = Object.keys(sessionStorage);
        keys.forEach(key => {
          if (key.startsWith('school_subject_')) {
            sessionStorage.removeItem(key);
          }
        });
        console.log('已清除所有学校的科目缓存');
      } catch (e) {
        console.warn('清除科目缓存失败:', e);
      }
    }
  },
};
